<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" title="字典列表" width="800px">
    <div class="form-box">
        <BasicForm @register="registerForm" />
    </div>
    <div class="table-box">
        <BasicTable
            @register="registerTable"
            :columns="columns"
            :dataSource="tableData"
            :canResize="false"
            :showIndexColumn="false"
            :striped="true"
            :bordered="true"
            :pagination="false"
            :actionColumn="actionColumn"
        >
        <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
            <TableAction
            :actions="[
                {
                    label: '编辑',
                    icon: 'ant-design:edit-outlined',
                    ifShow: true,
                    onClick: (e) => {
                        e.stopPropagation();
                        handleEdit(record);
                    },
                },
                {
                label: '删除',
                icon: 'ant-design:delete-outlined',
                ifShow:true,
                onClick: (e) => {
                    e.stopPropagation();
                    handleDelete(record);
                },
                },
            ]"
            />
        </template>
        </template>
        <template #toolbar>
            <a-button class="btn-box-item" @click="throttleReset">重置</a-button>
            <a-button class="btn-box-item" type="primary" @click="throttleSubmit">查询</a-button>
            <a-button
                class="btn-box-item"
                type="primary"
                @click="handleCreate">
                新增
            </a-button>
            </template>
        </BasicTable>
        <div class="flex py-2 items-center justify-end pagination-box">
            <a-pagination
            :show-total="(total) => `共 ${total} 条数据`"
            showSizeChanger
            size="small"
            :current="paginationInfo.data.current"
            :pageSize="paginationInfo.data.pageSize"
            :total="paginationInfo.data.total"
            @change="handlePageChange"
            />
        </div>
    </div>
  </BasicDrawer>
  <DictItemModal @register="registerModal"  @success="handelUpateTable" :dictId="dictId" />
</template>
<script lang="ts" setup>
  import { ref, reactive,h } from 'vue';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useModal } from '/@/components/Modal';
  import DictItemModal from './DictItemModal.vue';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { itemList, deleteItem } from '/@/api/dataDictionary/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useDebounceFn } from '@vueuse/core';
  import { useI18n } from '/@/hooks/web/useI18n';

  const { t } = useI18n();
  const code = ref('');
  const dictId = ref('');
  let tableData = reactive([]);
  // 表单内容
  const schemas: FormSchema[] = [
    {
        field: 'Code',
        component: 'Input',
        label: '编码',
        colProps: {
        span: 12,
        },
    },
  ]
// 表格表头
let columns: BasicColumn[] = [
      {
          title: '字典值',
          dataIndex: 'Value',
      },
      {
          title: '编码',
          dataIndex: 'Code',
      },
      {
          title: '名称',
          dataIndex: 'Name',
      },
      {
          title: '状态',
          dataIndex: 'Statustext',
      },
  ];
  // 分页信息
  let paginationInfo = reactive({
        data: {
            pageSize: 30,
            total: 0,
            current: 1,
        },
    })
  // 操作栏
  let actionColumn = {
      width: 150,
      title: '操作',
      dataIndex: 'action',
      // slots: { customRender: 'action' },
  };
  const { createConfirm, createMessage } = useMessage();
   //字典配置model
  const [registerModal, { openModal }] = useModal();
  const [enumModal, {openModal: openEnumModal }] = useModal();
  const [registerDrawer] = useDrawerInner(async (data) => {
    code.value = data.Code;
    dictId.value = data.dictId;
    getTableData();
  });
  //表格
  const [registerTable] = useTable();
  const [registerForm, { validateFields, setFieldsValue }] = useForm({
      labelWidth: 100,
      schemas: schemas,
      showActionButtonGroup: false,
      actionColOptions: {
      span: 24,
      },
  });
  const throttleSubmit = useDebounceFn(handleSubmit, 500);
  const throttleReset = useDebounceFn(handleResetFields, 500);
  // 重置按钮点击事件
  async function handleResetFields() {
      setFieldsValue({
          Code: '',
      });
      paginationInfo.data.current = 1;
      getTableData();
  }
  // 查询按钮点击事件
  async function handleSubmit() {
      try {
      let res = await validateFields();
      console.log(`output->res`, res);
      getTableData(res);
      } catch {}
  }
   // 获取字典值
   async function getTableData(params = {}) {
    try {
      // loading.value = true;
      let StatusObj = {
        1: '启用',
        2: '禁用',
      };
      let res = await itemList([
        {
            Code: '',
            dictTypeId: dictId.value,
            PageNO: paginationInfo.data.current,
            PageSize: paginationInfo.data.pageSize,
            ...params,
        },
      ]);
      paginationInfo.data.total = res.Total;
      tableData = res.Items.map((item) => {
        item.Statustext = StatusObj[item.Status];
        return item;
      });
      // loading.value = false;
    } catch (error) {
      // loading.value = false;
    }
  }
   // 分页事件
  function handlePageChange(page, pageSize) {
      paginationInfo.data.current = page;
      paginationInfo.data.pageSize = pageSize;
      getTableData();
  }

   // 新增或编辑成功事件
   function handelUpateTable() {
        getTableData();
    }
  /**
   * 新增
   */
  function handleCreate() {
    let record = {
      Status: 1,
      OrderNo: 100
    }
    openModal(true, {
      record,
      isUpdate: false,
    });
  }


  /**
   * 编辑
   */
  function handleEdit(record) {
    openModal(true, {
      record,
      isUpdate: true,
    });
  }
    // 删除
    function handleDelete(params) {
      createConfirm({
        iconType: 'warning',
        title: () => h('span', '温馨提示'),
        okText: '确认',
        content: () => h('span', `是否确认删除该字典（${params.Name}）`),
        onOk: async () => {
          try {
            await deleteItem([{id:params.Id}]);
            createMessage.success(t('layout.setting.operatingTitle'));
            getTableData();
            
          } catch (error) {
           
          }
        },
      });
  }

  
</script>
<style scoped lang="less">
  @prefix-cls: ~'@{namespace}-row-invalid';

  :deep(.@{prefix-cls}) {
    background: #f4f4f4;
    color: #bababa;
  }
</style>
